package com.hupu.jrs.ui.content

import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import butterknife.BindView
import butterknife.ButterKnife
import com.alibaba.fastjson.JSON
import com.hupu.jrs.Constants
import com.hupu.jrs.R
import com.hupu.jrs.bean.ImagePreview
import com.hupu.jrs.components.jockeyjs.JockeyHandler
import com.hupu.jrs.ui.BaseFragment
import com.hupu.jrs.ui.browser.BrowserActivity
import com.hupu.jrs.ui.imagepreview.ImagePreviewActivity
import com.hupu.jrs.ui.login.LoginActivity
import com.hupu.jrs.ui.post.PostActivity
import com.hupu.jrs.ui.report.ReportActivity
import com.hupu.jrs.ui.thread.list.ThreadListActivity
import com.hupu.jrs.ui.userprofile.UserProfileActivity
import com.hupu.jrs.util.SettingPrefUtil
import com.hupu.jrs.widget.H5Callback
import com.hupu.jrs.widget.JockeyJsWebView
import java.util.*
import javax.inject.Inject

/**
 * Created by sll on 2016/3/9.
 */
class ContentFragment : BaseFragment(), ContentPagerContract.View, H5Callback, JockeyJsWebView.OnScrollChangedCallback {

    @BindView(R.id.webView)
    internal var webView: JockeyJsWebView? = null

    @Inject
    internal var mContentPresenter: ContentPagerPresenter? = null

    private var tid: String? = null
    private var fid: String? = null
    private var pid: String? = null
    private var page: Int = 0

    override fun initInjector() {
        getComponent(ContentComponent::class.java).inject(this)
    }

    override fun initContentView(): Int {
        return R.layout.fragment_content
    }

    override fun getBundle(bundle: Bundle) {
        tid = bundle.getString("tid")
        fid = bundle.getString("fid")
        pid = bundle.getString("pid")
        page = bundle.getInt("page")
    }

    override fun initUI(view: View) {
        ButterKnife.bind(this, view)
        mContentPresenter!!.attachView(this)
        webView!!.setCallback(this)
        webView!!.initJockey()
        webView!!.onScrollChangedCallback = this
        webView!!.addJavascriptInterface(mContentPresenter!!.javaScriptInterface, "HuPuBridge")
    }

    override fun initData() {
        webView!!.loadUrl(if (SettingPrefUtil.getNightModel(getActivity()))
            "file:///android_asset/hupu_thread_night.html"
        else
            "file:///android_asset/hupu_thread.html")
    }

    override fun onReloadClicked() {
        mContentPresenter!!.onReload()
    }

    override fun onScroll(dx: Int, dy: Int) {
        if (Math.abs(dy) > 4) {
            val activity = getActivity() as ContentActivity
            activity?.setFloatingMenuVisibility(dy < 0)
        }
    }

    override fun showLoading() {
        showProgress(true)
    }

    override fun hideLoading() {
        showContent(true)
    }

    override fun onError() {
        setEmptyText("数据加载失败")
        showError(true)
    }

    override fun sendMessageToJS(handlerName: String, `object`: Any) {
        webView!!.sendMessageToJS(handlerName, `object`)
    }

    override fun loadUrl(url: String) {
        webView!!.loadUrl(url)
    }

    override fun showReplyUi(fid: String, tid: String, pid: String, title: String) {
        PostActivity.startActivity(getActivity(), Constants.TYPE_REPLY, fid, tid, pid, title)
    }

    override fun showReportUi(tid: String, pid: String) {
        ReportActivity.startActivity(getActivity(), tid, pid)
    }

    override fun showBrowserUi(url: String) {
        BrowserActivity.startActivity(getActivity(), url)
    }

    override fun showContentUi(tid: String, pid: String, page: Int) {
        ContentActivity.startActivity(getActivity(), "", fid.toString(), pid, page)
    }

    override fun showThreadListUi(fid: String) {
        ThreadListActivity.startActivity(getActivity(), fid)
    }

    override fun showUserProfileUi(uid: String) {
        UserProfileActivity.startActivity(getActivity(), uid)
    }

    override fun showLoginUi() {
        LoginActivity.startActivity(getActivity())
    }

    override fun onClose() {
        getActivity().finish()
    }

    override fun doPerform(map: Map<Any, Any>) {

    }

    override fun onPageFinished(webView: WebView, str: String) {
        mContentPresenter!!.onThreadInfoReceive(tid.toString(), fid.toString(), pid.toString(), page)
    }

    override fun onPageStarted(webView: WebView, str: String, bitmap: Bitmap) {

    }

    override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {

    }

    override fun setJockeyEvents() {
        webView!!.onJSEvent("showImg", object : JockeyHandler() {
            protected override fun doPerform(payload: Map<Any, Any>) {
                val preview = JSON.parseObject<ImagePreview>(JSON.toJSONString(payload), ImagePreview::class.java)
                ImagePreviewActivity.startActivity(getActivity(), preview.imgs!!.get(preview.index),
                        preview.imgs as ArrayList<String>)
            }
        })
        webView!!.onJSEvent("showUrl", object : JockeyHandler() {
            protected override fun doPerform(payload: Map<Any, Any>) {
                mContentPresenter!!.handlerUrl(payload["url"] as String)
            }
        })
        webView!!.onJSEvent("showUser", object : JockeyHandler() {
            protected override fun doPerform(payload: Map<Any, Any>) {
                UserProfileActivity.startActivity(getActivity(), payload["uid"] as String)
            }
        })
        webView!!.onJSEvent("showMenu", object : JockeyHandler() {
            protected override fun doPerform(payload: Map<Any, Any>) {
                val area = Integer.valueOf(payload["area"] as String)!!
                val index = Integer.valueOf(payload["index"] as String)!!
                val type = payload["type"] as String
                when (type) {
                    "light" -> mContentPresenter!!.addLight(area, index)
                    "rulight" -> mContentPresenter!!.addRuLight(area, index)
                    "reply" -> mContentPresenter!!.onReply(area, index)
                    "report" -> mContentPresenter!!.onReport(area, index)
                }
            }
        })
    }

    override fun openBrowser(url: String) {
        mContentPresenter!!.handlerUrl(url)
    }

    override fun onDestroy() {
        super.onDestroy()
        mContentPresenter!!.detachView()
        if (webView != null) {
            webView!!.destroy()
        }
    }

    companion object {

        fun newInstance(fid: String, tid: String, pid: String, page: Int): ContentFragment {
            val mFragment = ContentFragment()
            val bundle = Bundle()
            bundle.putString("fid", fid)
            bundle.putString("tid", tid)
            bundle.putString("pid", pid)
            bundle.putInt("page", page)
            mFragment.setArguments(bundle)
            return mFragment
        }
    }
}
